#include "lines.h"
#include "mask.h"

void swN(double l, double w, double g, int N)
{// draw N straight waveguide with uniform waveguide and gap
 // l: waveguide length
 // w: waveguide width
 // g: gap
 // N: waveguide number.
 
  if(N%2){
    for (int i=0; i<N/2; i++)
    {
      push_cp();
      sw2(l, w, g*2+w+i*2*(g+w));
      pop_cp();
    }
    sw(l, w);
  }
  else
  {
    int i =0;
    for (; i<N/2-1; i++)
    {
      push_cp();
      sw2(l, w, g+i*2*(g+w));
      pop_cp();
    }
      sw2(l, w, g+i*2*(g+w));
  //cp left at the middle of the end edge.
  }
}

void cwN(double r, double a, double w, double g, int N)  
{// draw N curved waveguide with uniform waveguide and gap
 // r: middle radius
 // a: turn angle
 // w: waveguide width
 // g: gap
 // N: waveguide number.

  if( fabs(r)-0.5*(w*N+g*(N-1))<0 ){//raise error if the internal edge radius <0.
    fprintf(stderr, "%e\n", fabs(r));
    fprintf(stderr, "VALUE ERROR in cwN: enlarge the radius or reduce the N");
    return;  
  } 
  if(N%2){
    for (int i=0; i<N/2; i++)
    {
      push_cp();
      cw2(r, a, w, g*2+w+i*2*(g+w));
      pop_cp();
    }
    cw(r, a, w);
  }
  else
  {
    int i =0;
    for (; i<N/2-1; i++)
    {
      push_cp();
      cw2(r, a, w, g+i*2*(g+w));
      pop_cp();
    }
      cw2(r, a, w, g+i*2*(g+w));
  //cp left at the middle of the end edge.
  }
}

double sbendN(double d, double r, double o, double w, double g, int N)
{// draw N s-bend waveguide cluster with uniform waveguide and gap
 // d, o, w follows the definition in sbend
 // r: middle radius
 // g: gap
 // N: waveguide number
  double a = acos(1- d*0.5/r);
  offset(o);
  cwN(r, a, w, g, N);
  offset(-2*o);
  cwN(-r, -a, w, g, N);
  offset(o);
  return 2*r*sin(a);
}

double sbend_series(double d, double r, double o, double w, double s, int N)
{// draw multiple cascaded s-bend with a separate straight waveguide.
 //d, r, o, w follow the definition in sbend
 //s: the straight waveguide length between adjacent s-bends
 //N: s-bend numbers
 // return the x span
  double z;
  for(int i=0; i<N; i++)
  {
    sw(s*0.5, w);
    z = sbend(((i%2)?-1:1)*d, r, o, w);
    sw(s*0.5, w);
  }
  return (z+s)*N;
}

